import 'dart:async';

import 'package:f_enjoy_plus/core/constants/app_colors.dart';
import 'package:f_enjoy_plus/components/Header.dart';
import 'package:f_enjoy_plus/utils/eventBus.dart';
import 'package:f_enjoy_plus/utils/http.dart';
import 'package:f_enjoy_plus/utils/toast.dart';
import 'package:f_enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  String phone = '';
  String code = '';
  int _countdown = 60; // 验证码倒计时
  bool _isCountdown = false; // 是否倒计时
  Timer? _timer;
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();

  /// 开启倒计时
  void _startCountdown() {
    if (_isCountdown) return;
    _isCountdown = true;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_countdown <= 0) {
        _timer?.cancel();
        _isCountdown = false;
        _countdown = 60;
      } else {
        setState(() {
          _countdown--;
        });
      }
    });
  }

  /// 获取验证码
  Future<void> _getCode() async {
    if (phone.isEmpty) {
      ToastUtils.show('请输入手机号');
      return;
    }
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phone)) {
      ToastUtils.show('请输入正确的手机号');
      return;
    }
    if (_isCountdown) {
      ToastUtils.show('请稍后再试');
      return;
    }

    _startCountdown();
    try {
      final res = await http.get('/code', params: {'mobile': phone});
      code = res['code'];
      Future.delayed(Duration(seconds: 2), () {
        setState(() {
          _isCountdown = false;
          _countdown = 60;
          _codeController.text = code;
          _timer?.cancel();
        });
      });
    } catch (e) {
      ToastUtils.show('获取验证码失败' + e.toString());
    }
  }

  /// 登录
  Future<void> _login() async {
    if (phone.isEmpty || code.isEmpty) {
      ToastUtils.show('请输入手机号和验证码');
      return;
    }
    try {
      final res = await http.post('/login', {'mobile': phone, 'code': code});
      ToastUtils.show('登录成功');
      await TokenManager.instance.setToken(res['token']);
      eventBus.fire(LoginEvent());
      Navigator.pop(context);
    } catch (e) {
      ToastUtils.show('登录失败' + e.toString());
    }
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _codeController.dispose();
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Header(title: '登录'),
      body: Container(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '登录',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 16),
            Text(
              '加入享+生活，开启美好生活',
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
            SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    keyboardType: TextInputType.phone,
                    maxLength: 11,
                    decoration: InputDecoration(hintText: '请输入手机号'),
                    onChanged: (value) {
                      phone = value;
                    },
                  ),
                ),
                SizedBox(width: 16),
                TextButton(
                  onPressed: () {
                    _getCode();
                  },
                  child:
                      _isCountdown ? Text('$_countdown秒后重新获取') : Text('获取验证码'),
                ),
              ],
            ),
            SizedBox(height: 16),
            TextField(
              controller: _codeController,
              keyboardType: TextInputType.number,
              maxLength: 6,
              decoration: InputDecoration(hintText: '请输入验证码'),
              onChanged: (value) {
                print(value + '---<');
                code = value;
              },
            ),
            SizedBox(height: 16),
            Text(
              '未注册手机号经验证后将自动登录',
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
            // SizedBox(height: 16),
            // Text('登录即表示同意《用户协议》', style: TextStyle(fontSize: 12, color: Colors.grey)),
            SizedBox(height: 32),
            ElevatedButton(
              onPressed: () {
                _login();
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.primary,
                minimumSize: Size(double.infinity, 50), // 设置宽度100%和高度
              ),
              child: Text('登录', style: TextStyle(fontSize: 16)),
            ),
          ],
        ),
      ),
    );
  }
}
